//
//  LocModel.m
//  lTTheOne
//
//  Created by AA on 2024/2/26.
//

#import "LocModel.h"
#import "GetLocFile.h"
#import "HeaderConfig.h"
#import "Masonry.h"
#import "UMLogFilesManager.h"
#import "UIColor+hexString.h"
#import "MSUserManager.h"

#define KtestType  0

@interface LocModel ()

@property(nonatomic,strong)GetLocFile *file;//一定要用实例变量或者属性，不要用局部变量

/**1--地区是否可注册 2--注册地点黑名单   3---地区切换社交功能   4 黑名单切换社交*/
@property (nonatomic,assign) NSInteger testType;
@property (nonatomic,assign,readwrite) BOOL isInBlackList;

@end

@implementation LocModel

+ (LocModel*)loc{
    
    static LocModel *g_locmodel;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        g_locmodel = [[LocModel alloc] init];
    });
    return g_locmodel;
}

- (id)init{
    
    if (self  = [super init]) {
        
        if (KtestType) {
            self.testType = 10;
        }
        
    }
    return self;
}

-(void)accredit{
    WEAKSELF
    self.file = [GetLocFile new];
    self.file.authBlock = ^(AuthLocationType type) {
        
        if(type == AuthLocationunsettled)//用户未决定
        {
            [weakSelf AddGlobalviewtext:@""];
        }
        else if (type == AuthLocationFuzzylocation)//模糊定位
        {
            [weakSelf AddGlobalviewtext:@"您所在的位置\n无法使用本应用"];
        }
        else if (type == AuthLocationAccept){//用户允许
            [weakSelf RemovGlobalview];
            
            
        }else{
//            (type == AuthLocationRefuse)//用户拒绝
//            (type == AuthLocationUnOpen)//用户未开启定位
//            (type == AuthLocationLimit)//访问受限
            [weakSelf AddGlobalviewtext:@"您所在的位置\n无法使用本应用"];
        }
    };
    
    [self GetLoc];
}

- (void)AddGlobalviewtext:(NSString*)text{
    
    [self RemovGlobalview];
    
    UIWindow *window = [UIApplication sharedApplication].keyWindow;

      UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, iphone_width, iphone_height)];
        v.tag = 1000099;
        v.backgroundColor = BacColor;
        [window addSubview:v];
    
    UIImageView *bimtimv = [[UIImageView alloc] initWithFrame:CGRectZero];
    [v addSubview:bimtimv];
    bimtimv.image = [UIImage imageNamed:@"breakdown"];
    [bimtimv mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.right.equalTo(v);
        make.bottom.equalTo(v);
    }];
    
    if (text != nil && ![text isEqualToString:@""]) {
        
        UILabel *textlab = [[UILabel alloc] initWithFrame:CGRectZero];
        textlab.numberOfLines = 2;
        textlab.text = text;
        textlab.textAlignment = NSTextAlignmentCenter;
        textlab.textColor = [UIColor whiteColor];
        textlab.font = [UIFont boldSystemFontOfSize:30];
        [v addSubview:textlab];
        [textlab mas_makeConstraints:^(MASConstraintMaker *make) {
           
            make.bottom.equalTo(bimtimv.mas_top).offset(-135);
            make.left.equalTo(v).offset(69);
            make.right.equalTo(v).offset(-69);
            make.centerX.equalTo(v);
        }];

    } 
}
- (void)RemovGlobalview{
    
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    UIView *v = [window viewWithTag:1000099];
    [v removeFromSuperview];
}

- (void)GetLocFinish:(void (^)(NSString*address))finishBlock{
    self.LocFinishBlock = finishBlock;
    [self GetLoc];
}

- (void)GetLoc{
    
    WEAKSELF
    self.file.placeMarkBlock = ^(CLPlacemark *placeMark) {//获取定位信息
        
        UMLog(@"placeMark.country=%@,\n placeMark.name=%@,\n placeMark.locality = %@,\n placeMark.subLocality=%@,\n thoroughfare=%@ \n subThoroughfare=%@ ",placeMark.country,placeMark.name,placeMark.locality, placeMark.subLocality,placeMark.thoroughfare,placeMark.subThoroughfare);
        
        UMLog(@"+++++++++>%f,%f",placeMark.location.coordinate.latitude,placeMark.location.coordinate.longitude);//获取当前定位的经纬度
        weakSelf.longitude = placeMark.location.coordinate.longitude;
        weakSelf.latitude  = placeMark.location.coordinate.latitude;
        
        if (KtestType) {

            NSString *test_City = [MSUserManager sharedManager].city_test;
            NSString *address_test = [MSUserManager sharedManager].address_test;
            
            /**1--地区是否可注册 2--注册地点黑名单   3---地区切换社交功能   4 黑名单切换社交*/
            switch (weakSelf.testType) {
                case 1:
                {
//                    test_City =@"乌鲁木齐市";
                    test_City =@"惠州市";
                }
                    break;
                case 2:
                {
                    address_test = @"公安局";
                }
                    break;
                case 3:
                {
                    test_City = [test_City isEqualToString:@"深圳市"]?@"乌鲁木齐市":@"深圳市";
                }
                    break;
                case 4:
                {
                    address_test = [address_test isEqualToString:@"公安局"]?placeMark.name:@"公安局";
                }
                    break;
                    
                default:
                    break;
            }
            
            [MSUserManager sharedManager].city_test = test_City;
            [MSUserManager sharedManager].address_test = address_test;;
            
            
            weakSelf.cityName = test_City?:placeMark.locality;
            weakSelf.Preciseaddress = address_test;
        }else{
            
            weakSelf.Preciseaddress = placeMark.name;
            weakSelf.cityName = placeMark.locality;
            if (kStringIsEmpty(placeMark.locality)==YES) {
                weakSelf.cityName = placeMark.administrativeArea;
            }
        }
        UMLog(@"test_City:%@___address_test:%@",weakSelf.cityName,weakSelf.Preciseaddress);
        !weakSelf.LocFinishBlock?:weakSelf.LocFinishBlock(weakSelf.Preciseaddress);
       
        
        //CLLocationCoordinate2D cll =  CLLocationCoordinate2DMake(placeMark.location.coordinate.latitude, placeMark.location.coordinate.longitude);
        
        /**
        [weakSelf GetInFotext:@"麦当劳" cll:cll distance:10000 Block:^(BOOL locisinfo) {
            !weakSelf.LocFinishBlock?:weakSelf.LocFinishBlock(weakSelf.Preciseaddress);
            
            if (locisinfo) {
                
                if (weakSelf.isShowbreakdown) {
                    weakSelf.isShowbreakdown(YES);
                }
                [weakSelf AddGlobalviewtext:@"服务器升级中"];
            }
            else {
                
                
                if (weakSelf.isShowbreakdown) {
                    weakSelf.isShowbreakdown(NO);
                }
//                    [weakSelf GetInFotext:@"派" cll:cll Block:^(BOOL locisinfo) {
//
//                        if (locisinfo) {
//
//                            if (weakSelf.isShowbreakdown) {
//                                weakSelf.isShowbreakdown(YES);
//                            }
//                            [weakSelf AddGlobalviewtext:@"服务器升级中"];
//                        }
//                        else{
//    
//                            if (weakSelf.isShowbreakdown) {
//                                weakSelf.isShowbreakdown(NO);
//                            }
//                        }
//                    }];
                
            }
        }];
        */
    };
    [self.file VicGetLocationAuth];
}


- (void)GetInFotext:(NSString*)text cll:(CLLocationCoordinate2D)cll distance:(int)distance Block:(LocisInfo)blcok{

    [self.file searchAroundWithText:text coordinate:cll range:distance andBackBlock:^(MKLocalSearchResponse *response) {
        
        if (response.mapItems.count>0) {
            
            BOOL box = NO;
            for(MKMapItem *mapItem in response.mapItems){
                UMLog(@"----------2>%@", mapItem.name);//获取周边信息
                UMLog(@"==========2>%f,%f",mapItem.placemark.location.coordinate.latitude,mapItem.placemark.location.coordinate.longitude);//获取周边信息的经纬度
                
                CLLocation *myis123 = [[CLLocation alloc] initWithLatitude:cll.latitude longitude:cll.longitude];
                
                //CLLocationCoordinate2DMake(22.643666, 114.238427);
                CLLocation *shanghaiLocation1 = [[CLLocation alloc] initWithLatitude:mapItem.placemark.location.coordinate.latitude longitude:mapItem.placemark.location.coordinate.longitude];
                
                CLLocationDistance detalDistance = [myis123 distanceFromLocation:shanghaiLocation1];
                UMLog(@"球面距离=[%lf米] [%lf公里]", detalDistance, detalDistance/1000.0);
                if (detalDistance <= distance) {
                    box = YES;
                }
            }
            if (box) {
                blcok(YES);
            } else {
                blcok(NO);
            }
        } else {
            blcok(NO);
        }
        
    }];
}

#pragma mark - getter

- (double)longitude{
    NSDictionary*dic=[[NSUserDefaults standardUserDefaults] dictionaryForKey:@"JMGLOBALLOCATION"];
    return [[dic objectForKey:@"longitude"] doubleValue];
}

-(double)latitude{
    NSDictionary*dic=[[NSUserDefaults standardUserDefaults] dictionaryForKey:@"JMGLOBALLOCATION"];
    return [[dic objectForKey:@"latitude"] doubleValue];
}

-(NSString*)Preciseaddress{
    NSDictionary*dic=[[NSUserDefaults standardUserDefaults] dictionaryForKey:@"JMGLOBALLOCATION"];
    return [dic objectForKey:@"address"];
}

-(NSString*)cityName{
    NSDictionary*dic=[[NSUserDefaults standardUserDefaults] dictionaryForKey:@"JMGLOBALLOCATION"];
    return [dic objectForKey:@"city"];;
}

@end
